'''
Created on 2013/5/20

@author: cat
'''

"""\
Scan for serial ports. Linux specific variant that also includes USB/Serial
adapters.

Part of pySerial (http://pyserial.sf.net)
(C) 2009 <cliechti@gmx.net>
"""

import serial
import glob
import threading
import time

        
class Serial_Thread(threading.Thread):
    _port = None
    _work = None
    
    
    def serial_init(self, port_name):    
        self._port = serial.Serial(port = port_name,
                                baudrate = 19200,
                                parity = serial.PARITY_NONE,
                                stopbits = serial.STOPBITS_ONE,
                                bytesize = serial.EIGHTBITS,
                                timeout = 0)

        if(self._port.isOpen() == False):
            self._port.open()
            
            
    def serial_clearBuffer(self, port):
        if port.isOpen():
            port.flushInput()
            port.flushOutput()          

    def serial_write(self, packet):
        if self._port.isOpen() == False:
            print("Comport closed")
            return
        
        self._port.write(packet)
        
    def serial_read(self, length):
        if self._port.isOpen() == False:
            print("Comport closed")
            return
        
        return list(self._port.read(length))
            
    def run(self):
        while True:
            if self._port.isOpen() == False:
                time.sleep(1)
                continue
            
            if self._work.empty():
                time.sleep(1)
                continue
            
            data = []
            if len(data) == 0:
                continue

                
                    
                    
                    
                       
                